<?php

class Core_Component_System_Controller_Backend_Component {

    public function __construct() {
        $GLOBALS[RC]->getHelper()->setLocation('{system.system}', '{system.component_index}');
    }

    public function indexAction($pageindex = 1, $pagesize = 20, $sort='id', $dir='asc') {
        $q = App::getModel('system/component')->getQuery();
        $list = $q->orderby($sort, $dir)->pagination($pageindex, $pagesize)->fetch();
        $count = $q->fetchCount();
        return $GLOBALS[RC]->getHelper()->templateResult(array('list' => $list, 'record_count' => $count));
    }

    public function createAction() {
        $GLOBALS[RC]->getHelper()->setLocation('{system.component_create}');
        return $GLOBALS[RC]->getHelper()->templateResult();
    }

    public function createPostAction(Core_Component_System_Model_Component $model) {
        try {
            $model->validate()->save();
            $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
            return $GLOBALS[RC]->getHelper()->historyResult('*/*/*/index');
        } catch (Core_Component_System_Exception $ex) {
            $GLOBALS[RC]->getMessager()->addError(
                    $GLOBALS[RC]->getLanguage()->__f('system.message.' . $ex->getMessage(), $model->getCode())
            );
            return $GLOBALS[RC]->getHelper()->templateResult();
        }
    }

    public function installAction() {
        $GLOBALS[RC]->getHelper()->setLocation('{system.component_install}');
        $req = $GLOBALS[RC]->getRequest();
        if ($req->isPost()) {
            $code = $req->getParameter('code');
            try {
                App::getBusiness('system/component')->install($code);
                $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
            } catch (Core_Component_System_Exception $ex) {
                $GLOBALS[RC]->getMessager()->addError(
                        $GLOBALS[RC]->getLanguage()->__f('system.message.' . $ex->getMessage(), $code)
                );
            }
        }

        return $GLOBALS[RC]->getHelper()->templateResult();
    }

    public function uninstallAction($id) {
        App::loadModel('system/component', $id)->delete();
        $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
        return $GLOBALS[RC]->getHelper()->historyResult('*/*/*/index');
    }

}